package controllers

import (
	"gitee.com/igolang/imoney/internal/app/system/services"
	"gitee.com/igolang/imoney/internal/app/system/tools"
	"gitee.com/igolang/imoney/internal/common/httpResp"
	"github.com/gin-gonic/gin"
)

func (c *user) Login(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	token, err := services.User.Login(ctx)
	if err != nil {
		if httpResp.IsErrorCode(err) {
			httpResp.ErrorResponse(httpResp.ErrCodeInvalidPassword, r)
		} else {
			httpResp.ErrorResponse(err, r)
		}
		return
	}
	r.Data = gin.H{
		"token": token,
	}
}

func (c *user) Logout(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	err := services.User.Logout(ctx)
	if err != nil {
		if httpResp.IsErrorCode(err) {
			httpResp.ErrorResponse(httpResp.ErrCodeInvalidPassword, r)
		} else {
			httpResp.ErrorResponse(err, r)
		}
		return
	}
}

func (c *user) Captcha(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	data, err := services.User.Captcha(ctx)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	r.Data = data
}

func (c *user) LoginUnlock(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	if err := services.User.Unlock(ctx); err != nil {
		httpResp.ErrorResponse(err, r)
	}
}

func (c *user) LoginUser(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	r.Data = tools.GetUserInfo(ctx)
}
